<template>
  <div>
    <!-- 顶部导航区 -->
    <van-nav-bar
      left-text="取消"
      title="昵称"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="EditSuccess"
    ></van-nav-bar>
    <!-- 文本框 -->
    <div class="field-container">
      <van-field
        v-model="newName"
        rows="1"
        autosize
        type="textarea"
        maxlength="7"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'EditName',
  props: {
    name: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      newName: this.name
    }
  },
  methods: {
    async EditSuccess () {
      this.$toast.loading({
        message: '保存中！',
        forbidClick: true
      })
      try {
        await this.$https.patch('/app/v1_0/user/profile', {
          name: this.newName
        })
        this.$emit('success-name', this.newName)
        this.$emit('close')
        this.$toast.success('修改成功！')
      } catch (error) {
        if (error.response.status === 409) {
          this.$toast.fail('昵称已经存在！')
        }
        if (error.response.status === 400) {
          this.$toast.fail('昵称不能为空！')
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.field-container {
  padding: 8px;
}
</style>
